package com.toolmanrln.security.component;

import com.toolmanrln.common.api.ResponseData;
import com.toolmanrln.common.util.ResponseUtil;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ToolMan.RLN
 * @since 2020-05-20 16:04
 */
@Component
public class RestfulAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String message;
        if (exception instanceof LockedException) {
            message = "账户被锁定，请联系管理员!";
        } else if (exception instanceof CredentialsExpiredException) {
            message = "密码过期，请联系管理员!";
        } else if (exception instanceof AccountExpiredException) {
            message = "账户过期，请联系管理员!";
        } else if (exception instanceof DisabledException) {
            message = "账户被禁用，请联系管理员!";
        } else if (exception instanceof BadCredentialsException) {
            message = "用户名或者密码输入错误，请重新输入!";
        } else if (exception instanceof AuthenticationServiceException) {
            message = exception.getMessage();
        } else {
            message = "登录失败，请联系管理员！";
        }
        ResponseUtil.responseToJson(response, ResponseData.failed(message));
    }
}
